package com.loong.common.executor;

import com.alibaba.fastjson.JSONObject;
import com.loong.common.enumerate.ResultCode;
import com.loong.common.exception.ExceptionDTO;
import com.loong.common.exception.GlobalException;
import com.loong.common.function.CommonConsumer;
import com.loong.common.function.CommonFunction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
@Component
public class BatchExecutor {

  public <T> void batchExecute(Collection<T> collection, CommonFunction<T,String> getId, CommonConsumer<T> executor){
      List<ExceptionDTO> exceptionDTOS = new ArrayList<>();
      collection.forEach(item->{
          try {
              executor.apply(item);
          }catch (Exception e){
              log.error("批量操作出现异常:{}-->{}",item,e);
              if(e instanceof GlobalException){
                  exceptionDTOS.add(ExceptionDTO.builder()
                          .errorData(((GlobalException) e).getExtraMessage())
                          .id(getId.apply(item))
                          .build());
              }else {
                  exceptionDTOS.add(ExceptionDTO.builder()
                          .errorData(e.getMessage())
                          .id(getId.apply(item))
                          .build());
              }
          }
      });
      if(exceptionDTOS.size()>1){
          throw new GlobalException(ResultCode.BATCH_ERROR, JSONObject.toJSONString(exceptionDTOS));
      }
  }
}
